package com.atomdayl.domain.therecipe.network;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.atomdayl.domain.therecipe.R;
import com.atomdayl.domain.therecipe.utils.CheckNetWorkUtils;

import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 网络配置Manager。我这边没有去维护一个网络队列了
 * Created by David on 2016/6/4.
 */
public class ThreadManager {
    public static Dialog dialog;
    public static Thread thread = null;
    public static boolean isGo = true;
    public ThreadPoolExecutor threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(1);

    private ThreadManager() {
        int maximumPoolSize = Runtime.getRuntime().availableProcessors();
        if (maximumPoolSize > 1) {
            threadPool.setCorePoolSize(maximumPoolSize);
        }
    }

    private static ThreadManager mInstance;

    public static ThreadManager getInstance() {
        if(mInstance == null) {
            synchronized (ThreadManager.class) {
                if(mInstance == null) {
                    mInstance = new ThreadManager();
                }
            }
        }
        return mInstance;
    }

    public static Toast mNoNetworkToast;
    //当前是否正在显示无网络的toast提示，用于防止无网络时频繁弹出Toast提示
    public static boolean isNoNetworkToastShowing;
    public static Handler mMainHandler = new Handler(Looper.getMainLooper());

    private void showNoNetworkToast(Context context, String msg) {
       Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    public static HashMap<Integer, Boolean> mTaskList = new HashMap<Integer, Boolean>();
    private  Handler handler = new Handler();

    /**
     * 处理Response问题
     * @param resultData
     * @param taskId
     * @return  true ： 返回结果成功  false ： 返回结果失败
     */
    private boolean dealWithResonse(Context context, String resultData, int taskId) {
        if ("网络异常".equals(resultData)) {
            Toast.makeText(context, "网络异常", Toast.LENGTH_SHORT).show();
            if (dialog != null && dialog.getWindow() != null && dialog.isShowing()) {
                dialog.cancel();
            }
        } else if (mTaskList.containsKey(taskId)) {
            if (dialog != null && dialog.getWindow() != null && dialog.isShowing()) {
                try {
                    dialog.dismiss();
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    public void exeTask(final Context context, final ThreadCallback callBack, final int taskId,
                               final String postParameter, final String reqUrl) {
        ThreadManager.isGo = true;
        if (!mTaskList.containsKey(taskId))
            mTaskList.put(taskId, true);

        NetworkManager.stop = false;
        if (!NetworkManager.checkNetWork(context)) {
            return;
        }

        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                final String resultData = sendToServer(context, taskId, postParameter, reqUrl);
                if (isGo) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if(dealWithResonse(context, resultData,taskId)) {
                                callBack.onCallbackSucceedFromThread(resultData, taskId);
                            }
                        }
                    });
                }
            }
        });
        isGo = true;
        threadPool.execute(thread);
    }

    public void exeTask(final Context context, final ThreadCallback callBack, final int taskId,
                        final String postParameter, final String reqUrl,
                        final boolean dialogIsCancelable, final boolean dialogIsAppear) {
        ThreadManager.isGo = true;
        NetworkManager.stop = false;
        if (!mTaskList.containsKey(taskId))
            mTaskList.put(taskId, true);
        if (!CheckNetWorkUtils.netWorkIsAvailable(context)) {
            if (dialogIsAppear) {
                if((context instanceof Activity)&&!((Activity)context).isFinishing()) {
                    dialog = showNetworkDialog(context,
                            dialogIsCancelable, new DialogInterface.OnCancelListener() {
                                @Override
                                public void onCancel(DialogInterface arg0) {
                                    NetworkManager.stop = true;
                                    isGo = false;
                                    if (mTaskList.containsKey(taskId))
                                        mTaskList.remove(taskId);
                                }
                            });
                }

            } else {
                showNoNetworkToast(context, "没有可用的网络");
                // callBack.onCancelFromThread("没有可用的网络", taskId);
                // callBack.onCallbackFromThread("没有可用的网络", taskId);
            }
            callBack.onCancelFromThread("没有可用的网络", taskId);
            return;
        }

        if (dialogIsAppear) {
            if((context instanceof Activity)&&!((Activity) context).isFinishing()) {
                dialog = showProgress(context, dialogIsCancelable,
                        new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface arg0) {
                                NetworkManager.stop = true;
                                isGo = false;
                                if (mTaskList.containsKey(taskId))
                                    mTaskList.remove(taskId);
                                callBack.onCancelFromThread("终止网络请求", taskId);
                                // if(isGoBack)
                                // ((Activity)context).finish();
                            }
                        });
            }
        }

        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                final String resultData = sendToServer(context, taskId, postParameter, reqUrl);
                if (isGo) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if(dealWithResonse(context,resultData,taskId)) {
                                callBack.onCallbackSucceedFromThread(resultData, taskId);
                            }
                        }
                    });
                }
            }
        });
        isGo = true;
        threadPool.execute(thread);
    }

    public void exeGetTask(final Context context, final ThreadCallback callBack,
                           final int taskId, final String reqUrl,
                           final boolean dialogIsCancelable, final boolean dialogIsAppear) {

        ThreadManager.isGo = true;
        NetworkManager.stop = false;
        if (!mTaskList.containsKey(taskId))
            mTaskList.put(taskId, true);

        if (!CheckNetWorkUtils.netWorkIsAvailable(context)) {
            if (dialogIsAppear) {
                if((context instanceof Activity)&&!((Activity)context).isFinishing()) {
                    dialog = showNetworkDialog(context,
                            dialogIsCancelable, new DialogInterface.OnCancelListener() {
                                @Override
                                public void onCancel(DialogInterface arg0) {
                                    NetworkManager.stop = true;
                                    isGo = false;
                                    if (mTaskList.containsKey(taskId))
                                        mTaskList.remove(taskId);
                                    callBack.onCancelFromThread("没有可用的网络", taskId);
                                    // if(isGoBack)
                                    // ((Activity)context).finish();
                                }
                            });
                }
            } else {
                showNoNetworkToast(context, "没有可用的网络");
                callBack.onCancelFromThread("没有可用的网络", taskId);
                // callBack.onCallbackFromThread("没有可用的网络", taskId);
            }
            return;
        }
        if (dialogIsAppear) {
            if((context instanceof Activity)&&!((Activity)context).isFinishing()) {
                dialog = showProgress(context, dialogIsCancelable,
                        new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface arg0) {
                                NetworkManager.stop = true;
                                isGo = false;
                                if (mTaskList.containsKey(taskId))
                                    mTaskList.remove(taskId);
                                callBack.onCancelFromThread("终止网络请求", taskId);
                                // if(isGoBack)
                                // ((Activity)context).finish();
                            }
                        });
            }
        }

        thread = new Thread(new Runnable() {
            @Override
            public void run() {

                final String resultData = NetworkManager.getInstance().doGet(context, reqUrl);
                if (isGo) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if(dealWithResonse(context, resultData,taskId)) {
                                callBack.onCallbackSucceedFromThread(resultData, taskId);
                            }
                        }
                    });
                }
            }
        });
        isGo = true;
        threadPool.execute(thread);
    }


    public static String sendToServer(Context context, int taskId, String postParameter,
                                      String reqUrl) {
        String resultData = NetworkManager.getInstance().doPost(context, reqUrl, postParameter);

        return resultData;
    }

    /**
     * 关闭，并等待任务执行完成，不接受新任务
     */
    public void shutdown() {
        if (threadPool != null) {
            threadPool.shutdown();
        }
    }

    /**
     * 关闭，立即关闭，并挂起所有正在执行的线程，不接受新任务
     */
    public void shutdownRightnow() {
        if (null != threadPool) {
            threadPool.shutdownNow();
            try {
                // 设置超时极短，强制关闭所有任务
                threadPool.awaitTermination(1, TimeUnit.MICROSECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public  Dialog showNetworkDialog(final Context context,
                                           boolean cancelable, DialogInterface.OnCancelListener cancelListener) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("没有可用的网络");
        builder.setMessage("请开启GPRS或WIFI网络连接");
        final Dialog dlg = builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {

                Intent intent = new Intent("android.settings.WIRELESS_SETTINGS");
                context.startActivity(intent);
            }
        }).setNeutralButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.cancel();
            }
        }).create();
        dlg.setCancelable(cancelable);
        dlg.setCanceledOnTouchOutside(false);
        dlg.setOnCancelListener(cancelListener);
        dlg.show();
        return dlg;
    }

    public static ProgressDialog showProgress(Context context,
                                              boolean cancelable, DialogInterface.OnCancelListener cancelListener) {
        View layout = LayoutInflater.from(context).inflate(R.layout.model_progress_dlg, null);
        final ProgressDialog dlg = new ProgressDialog(context);
        dlg.setCancelable(cancelable);
        dlg.setCanceledOnTouchOutside(false);
        dlg.setIndeterminate(false);
        dlg.setOnCancelListener(cancelListener);
        dlg.show();
        if (cancelable) {
            layout.findViewById(R.id.progress_btn_close).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    if (null != dlg && dlg.isShowing())
                        // dlg.dismiss();
                        dlg.cancel();
                }
            });
        } else {
            layout.findViewById(R.id.progress_btn_close).setVisibility(View.GONE);
        }
        dlg.setContentView(layout);
        return dlg;
    }

}
